<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import ScheduleCard from './components/ScheduleCard.vue'
import { getScheduleList } from '@/services/home.ts'
import CustomNavbar from './components/CustomNavbar.vue'
import { useMemberStore } from '@/stores'
import type {
  ScheduleItem,
  ScheduleParams,
  SmartScheduleSuggestion,
  ScheduleConflict,
  ScheduleRecommendation,
} from '@/types/schedule'
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'
import { formatDate } from '@/utils'
import AddScheduleModal from './components/AddScheduleModal.vue'
import SmartScheduleGenerator from './components/SmartScheduleGenerator.vue'

// 获取会员Store实例
const memberStore = useMemberStore()

// 滚动位置同步
const tableScrollRef = ref<HTMLDivElement | null>(null)
const gridScrollRef = ref<HTMLDivElement | null>(null)
const scrollLeft = ref(0)

// 星期标题
const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

// 课程数据
const scheduleList = ref<ScheduleItem[]>([])
// 分页参数
const schedulePage = ref<ScheduleParams>({ pageNum: 1, pageSize: 10 })
const hasMoreSchedule = ref(true)
const isLoading = ref(false)
const isTriggered = ref(false)

// 智能课程生成相关
const showAddModal = ref(false)
const showSmartGenerator = ref(false)
const smartSuggestions = ref<SmartScheduleSuggestion[]>([])
const selectedTeacherId = ref()

// 权限控制
const canAddSchedule = computed(() => {
  const userInfo = memberStore.profile
  return userInfo?.role === 'teacher' || userInfo?.role === 'organ'
})

// 当前日期和周范围
const currentDate = ref(new Date())
const currentWeekRange = computed(() => {
  const now = currentDate.value
  const day = now.getDay() || 7
  const monday = new Date(now)
  monday.setDate(now.getDate() - day + 1)
  const sunday = new Date(monday)
  sunday.setDate(monday.getDate() + 6)

  const formatDate = (date: Date) => {
    return `${date.getFullYear()}年${(date.getMonth() + 1).toString().padStart(2, '0')}月${date
      .getDate()
      .toString()
      .padStart(2, '0')}日`
  }

  return `${formatDate(monday)}-${formatDate(sunday).slice(8)}`
})

// 上一周/下一周切换
const prevWeek = () => {
  currentDate.value = new Date(currentDate.value.getTime() - 7 * 24 * 60 * 60 * 1000)
  loadData()
}

const nextWeek = () => {
  currentDate.value = new Date(currentDate.value.getTime() + 7 * 24 * 60 * 60 * 1000)
  loadData()
}

// 加载数据
const loadData = async () => {
  isLoading.value = true
  schedulePage.value.pageNum = 1
  await getScheduleListData(schedulePage.value)
  isLoading.value = false
}

// 获取课程列表
const getScheduleListData = async (pageParams: ScheduleParams) => {
  const now = currentDate.value
  const day = now.getDay() || 7
  const monday = new Date(now)
  monday.setDate(now.getDate() - day + 1)
  monday.setHours(0, 0, 0, 0)
  const sunday = new Date(monday)
  sunday.setDate(monday.getDate() + 6)
  sunday.setHours(23, 59, 59, 999)

  pageParams.startDateStart = formatDate(monday)
  pageParams.startDateEnd = formatDate(sunday)

  if (pageParams.pageNum === 1) {
    scheduleList.value = []
    hasMoreSchedule.value = true
  }

  if (!hasMoreSchedule.value) return

  try {
    const res = await getScheduleList(pageParams)

    if (pageParams.pageNum === 1) {
      scheduleList.value = res.data.rows
    } else {
      scheduleList.value = [...scheduleList.value, ...res.data.rows]
    }

    hasMoreSchedule.value = res.data.rows.length === pageParams.pageSize
    schedulePage.value.pageNum = pageParams.pageNum

    // 智能分析课程数据
    if (canAddSchedule.value) {
      analyzeScheduleData()
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
  }
}

// 智能分析课程数据
const analyzeScheduleData = () => {
  // 基于历史课程数据生成智能建议
  const teacherScheduleMap = new Map<string, ScheduleItem[]>()

  scheduleList.value.forEach((schedule) => {
    if (!teacherScheduleMap.has(schedule.teacherId)) {
      teacherScheduleMap.set(schedule.teacherId, [])
    }
    teacherScheduleMap.get(schedule.teacherId)?.push(schedule)
  })

  // 生成每个教师的建议
  const suggestions: SmartScheduleSuggestion[] = []
  teachers.value.forEach((teacher) => {
    const teacherSchedules = teacherScheduleMap.get(teacher.id) || []
    suggestions.push({
      teacherId: teacher.id,
      teacherName: teacher.name,
      availableSlots: generateAvailableSlots(teacherSchedules),
      conflicts: [],
      recommendations: generateRecommendations(teacherSchedules),
    })
  })

  smartSuggestions.value = suggestions
}

// 生成可用时间段
const generateAvailableSlots = (schedules: ScheduleItem[]) => {
  const slots = []
  const occupiedSlots = schedules.map((s) => ({
    day: new Date(s.startDatetime).getDay() || 7,
    start: s.startDatetime,
    end: s.endDatetime,
  }))

  // 生成工作时间段（9:00-18:00）
  for (let day = 1; day <= 7; day++) {
    for (let hour = 9; hour < 18; hour++) {
      const isOccupied = occupiedSlots.some(
        (slot) =>
          slot.day === day &&
          new Date(slot.start).getHours() <= hour &&
          new Date(slot.end).getHours() > hour,
      )

      if (!isOccupied) {
        slots.push({
          dayOfWeek: day - 1,
          startTime: `${hour.toString().padStart(2, '0')}:00`,
          endTime: `${(hour + 1).toString().padStart(2, '0')}:00`,
        })
      }
    }
  }

  return slots
}

// 生成推荐
const generateRecommendations = (schedules: ScheduleItem[]) => {
  const recommendations: ScheduleRecommendation[] = []
  const timeDistribution = new Map<number, number>()

  // 统计教师在不同时间段的习惯
  schedules.forEach((schedule) => {
    const day = new Date(schedule.startDatetime).getDay() || 7
    const hour = new Date(schedule.startDatetime).getHours()
    const key = day * 100 + hour
    timeDistribution.set(key, (timeDistribution.get(key) || 0) + 1)
  })

  // 基于习惯生成推荐
  timeDistribution.forEach((count, key) => {
    const day = Math.floor(key / 100)
    const hour = key % 100

    if (count >= 2) {
      // 出现2次以上的时间段
      recommendations.push({
        dayOfWeek: day - 1,
        startTime: `${hour.toString().padStart(2, '0')}:00`,
        endTime: `${(hour + 1).toString().padStart(2, '0')}:00`,
        probability: Math.min(count * 0.3, 0.9),
        reason: `基于历史偏好：${count}次相同时间段安排`,
      })
    }
  })

  return recommendations
}

// 下拉刷新
const onRefresherrefresh = async () => {
  isTriggered.value = true
  schedulePage.value.pageNum = 1
  await getScheduleListData(schedulePage.value)
  isTriggered.value = false
}

// 生成每日日期标签
const dailyDateLabels = computed(() => {
  const now = currentDate.value
  const day = now.getDay() || 7
  const labels = []

  for (let i = 0; i < 7; i++) {
    const date = new Date(now)
    date.setDate(now.getDate() - day + 1 + i)
    labels.push(`${date.getMonth() + 1}-${date.getDate()}`)
  }
  return labels
})

// 提取所有老师信息
const teachers = computed(() => {
  const teacherMap = new Map<string, { id: string; name: string }>()
  scheduleList.value.forEach((schedule) => {
    if (schedule.teacherId && schedule.teacherName) {
      teacherMap.set(schedule.teacherId, {
        id: schedule.teacherId,
        name: schedule.teacherName,
      })
    }
  })
  return Array.from(teacherMap.values())
})

// 根据老师ID和星期几获取课程
const getScheduleByTeacherAndDay = (teacherId: string, dayIndex: number) => {
  return scheduleList.value.filter((schedule) => {
    if (schedule.teacherId !== teacherId) return false
    const date = new Date(schedule.startDatetime.replace(/-/g, '/'))
    const day = date.getDay() || 7
    return day - 1 === dayIndex
  })
}

// 打开添加课程弹窗
const openAddModal = () => {
  if (memberStore.profile?.role === 'teacher') {
    selectedTeacherId.value = memberStore.profile.userId
  }
  showAddModal.value = true
}

// 打开智能生成器
const openSmartGenerator = () => {
  showSmartGenerator.value = true
}

// 添加新课程
const handleAddSchedule = (schedule: ScheduleItem) => {
  scheduleList.value.push(schedule)
  uni.showToast({
    title: '课程添加成功',
    icon: 'success',
  })
  // 重新分析数据
  analyzeScheduleData()
}

// 表格滚动事件处理
const onTableScroll = (e: any) => {
  scrollLeft.value = e.detail.scrollLeft
}

const onGridScroll = (e: any) => {
  if (tableScrollRef.value) {
    tableScrollRef.value.scrollLeft = e.detail.scrollLeft
  }
}

onMounted(() => {
  if (gridScrollRef.value) {
    gridScrollRef.value.addEventListener('scroll', onGridScroll)
  }
  loadData()
})

onUnmounted(() => {
  if (gridScrollRef.value) {
    gridScrollRef.value.removeEventListener('scroll', onGridScroll)
  }
})
</script>

<template>
  <view class="schedule-container">
    <!-- 自定义导航栏 -->
    <CustomNavbar title="老师课表" />

    <!-- 日期选择器 -->
    <view class="date-picker">
      <uni-icons type="left" size="14" @click="prevWeek" color="#0a0a0a" />
      <view class="date-range">{{ currentWeekRange }}</view>
      <uni-icons type="right" size="14" @click="nextWeek" color="#0a0a0a" />

      <!-- 智能生成按钮（教师/机构可见） -->
      <view v-if="canAddSchedule" class="action-buttons">
        <button class="smart-btn" @click="openSmartGenerator" size="mini" type="primary">
          <uni-icons type="compose" size="14" color="#fff" />
          智能生成
        </button>
      </view>
    </view>

    <!-- 表格容器 -->
    <scroll-view
      scroll-x
      class="table-container"
      :scroll-with-animation="true"
      @scroll="onTableScroll"
      ref="tableScrollRef"
    >
      <view class="table-wrapper">
        <!-- 表头行 -->
        <view class="header-row">
          <view class="teacher-header">教师</view>
          <view class="weekday" v-for="(date, index) in dailyDateLabels" :key="index">
            <text class="date-text">{{ weekdays[index] }}</text>
            <text class="weekday-text">{{ date }}</text>
          </view>
        </view>

        <!-- 课程网格容器 -->
        <scroll-view
          :scroll-y="true"
          class="grid-container"
          :enable-back-to-top="true"
          :refresher-enabled="true"
          @refresherrefresh="onRefresherrefresh"
          :refresher-triggered="isTriggered"
          :scroll-left="scrollLeft"
          ref="gridScrollRef"
        >
          <view class="schedule-grid">
            <view v-for="teacher in teachers" :key="teacher.id" class="teacher-row">
              <view class="teacher-column">
                <text class="teacher-name">{{ teacher.name }}</text>
              </view>
              <view class="day-column" v-for="(day, index) in 7" :key="index">
                <ScheduleCard
                  v-for="schedule in getScheduleByTeacherAndDay(teacher.id, index)"
                  :key="schedule.id"
                  :schedule="schedule"
                />
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </scroll-view>

    <!-- 悬浮添加按钮（教师/机构可见） -->
    <view v-if="canAddSchedule" class="fab-container">
      <button class="fab-add" @click="openAddModal">
        <uni-icons type="plus" size="24" color="#fff" />
      </button>
    </view>

    <!-- 添加课程弹窗 -->
    <AddScheduleModal
      v-model:visible="showAddModal"
      :teacher-id="selectedTeacherId"
      :suggestions="smartSuggestions"
      @add="handleAddSchedule"
    />

    <!-- 智能生成器 -->
    <SmartScheduleGenerator
      v-model:visible="showSmartGenerator"
      :suggestions="smartSuggestions"
      @generate="(schedules: ScheduleItem[]) => schedules.forEach(handleAddSchedule)"
    />
  </view>
</template>

<style lang="scss" scoped>
.schedule-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: $bg-color;
  box-sizing: border-box;
}

.date-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: $card-bg;
  border-bottom: 1rpx solid $border-color;
}

.date-range {
  font-size: 32rpx;
  font-weight: 600;
  color: $text-main;
}

.action-buttons {
  display: flex;
  gap: 16rpx;
}

.smart-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 16rpx;
  font-size: 24rpx;
  border-radius: 20rpx;
}

.table-container {
  width: 100%;
  overflow-x: auto;
  flex: 1;
  background-color: $card-bg;
}

.table-wrapper {
  width: fit-content;
  display: flex;
  flex-direction: column;
}

.header-row {
  display: flex;
  background-color: $card-bg;
  border-bottom: 2rpx solid $primary-color;
  position: sticky;
  top: 0;
  z-index: 20;
}

.teacher-header {
  width: 200rpx;
  height: 100rpx;
  text-align: center;
  padding: 10rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: 600;
  color: $text-main;
  border-right: 1rpx solid $border-color;
  background-color: $card-bg;
  position: sticky;
  left: 0;
  z-index: 30;
}

.teacher-row {
  display: flex;
  width: 100%;
  border-bottom: 1rpx solid $border-color;
}

.teacher-column {
  width: 200rpx;
  padding: 20rpx 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1rpx solid $border-color;
  background-color: $card-bg;
  position: sticky;
  left: 0;
  z-index: 20;
}

.teacher-name {
  font-size: 28rpx;
  font-weight: 600;
  color: $text-main;
}

.weekday {
  width: 240rpx;
  height: 100rpx;
  text-align: center;
  padding: 10rpx 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-right: 1rpx solid $border-color;
}

.weekday:last-child {
  border-right: none;
}

.date-text {
  font-size: 28rpx;
  font-weight: 600;
  color: $text-main;
}

.weekday-text {
  font-size: 24rpx;
  color: $text-secondary;
  margin-top: 5rpx;
}

.day-column {
  width: 240rpx;
  padding: 10rpx 5rpx;
  border-right: 1rpx solid $border-color;
  min-height: 300rpx;
}

.fab-container {
  position: fixed;
  bottom: 120rpx;
  right: 40rpx;
  z-index: 1000;
}

.fab-add {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: $primary-color;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  border: none;
}
</style>
